/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.turboconnard.core;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView.Renderer;

import com.turboconnard.display.Stage;
import com.turboconnard.tools.Textures;

/**
 * Render a pair of tumbling cubes.
 */

public class MainRenderer implements Renderer {
	private static final int PIXELUNIT = 320;
	private MainActivity context;
	
	private int near;
	private int far;
	private float cameraz;

	private Stage stage;
	
	public Agd agd;
	public MainRenderer(MainActivity pContext) {
	
		context = pContext;
		stage = new Stage(0,0,PIXELUNIT);	
		
	}

	public void onSurfaceChanged(GL10 gl, int w, int h) {
		stage.resize(w,h);
		Textures.init(gl,context);				
		
		near = 2;
		far = 90000;
		float ratio = (float) w / h;		
		
		gl.glViewport(0, 0, w, h);
		
		//DISABLE TO 2D mode
		//ENABLE FOR 3D mode
			gl.glEnable(GL10.GL_DEPTH_TEST);	
		//----------------------------------
		gl.glDisable(GL10.GL_DITHER);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glFrustumf(-ratio,ratio,-1,1,near, far);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
	
		cameraz = ( 1 / (float) Math.tan(Math.atan2( ( PIXELUNIT /((float) h)) ,near)));
		
		
		agd = context.go();
		stage.activity = context;
		context.agd = agd;
	}
	public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
	
	}
	/**
	 * Draw the view content
	 * @see android.view.View#onDraw(android.graphics.Canvas)
	 */
	public void onDrawFrame(GL10 gl) {
		agd._update();
		gl.glClearColor(255.0f,0.0f , 0.0f, 1f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BITS);
		gl.glLoadIdentity();
		gl.glTranslatef(-stage.width/2*stage.correction, stage.height/2*stage.correction,-cameraz);//-(z*near));
		//gl.glTranslatef(0, 0,-cameraz);//-(z*near));
		stage.draw(gl);
	}
	//------------------------------------------------------------------------
}
